#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/asio.hpp>
#include "Listener.hpp"
#include "Request.hpp"

Listener::Listener(int port)
	        : acceptor(io, ip::tcp::endpoint(ip::tcp::v4(), port))
        	, socket(io) {
        start_accept();
    }

void Listener::start_accept() {
	Request *r = new Request(io);
	acceptor.async_accept(r->socket(), boost::bind(&Listener::handle_accept, this, r, placeholders::error));
}

void Listener::handle_accept(Request *r, const boost::system::error_code& error) {
	if (!error) {
		// Get the request object who will work with this client and setup on_read to it
		r->start( boost::system::error_code() );
	}
	start_accept(); // Accept next
}

void Listener::run() {
	boost::thread thr1( boost::bind(&Listener::ioloop, this) );
	boost::thread thr2( boost::bind(&Listener::ioloop, this) );
//	boost::thread thr3( boost::bind(&Listener::ioloop, this) );
	thr1.join();
	thr2.join();
//	thr3.join();
// */
//	ioloop();
}
